<template>
    <div class="auth-page">
  <div class="container page">
    <div class="row">

      <div class="col-md-6 offset-md-3 col-xs-12">
        <h1 class="text-xs-center">{{isLogin=='login'?'Sign In':'Sign Up'}}</h1>
        <p class="text-xs-center">
            <nuxt-link to="/login" v-if="isLogin=='register'">Have an account?</nuxt-link>
            <nuxt-link to="/register" v-else>Need an account?</nuxt-link>
        </p>

        <ul class="error-messages">
          <template v-for="(msg,filed) in errors">
            <li v-for="(message,index) in msg" :key="index">{{filed}}：{{message}}</li>
          </template>
          
        </ul>

        <form @submit.prevent='onSubmit'>
          <fieldset class="form-group" v-if="isLogin=='register'">
            <input class="form-control form-control-lg" type="text" placeholder="Your Name" required v-model="user.username">
          </fieldset>
          <fieldset class="form-group">
            <input class="form-control form-control-lg" type="email" placeholder="Email" v-model="user.email" required>
          </fieldset>
          <fieldset class="form-group">
            <input class="form-control form-control-lg" type="password" placeholder="Password" v-model="user.password" required>
          </fieldset>
          <button class="btn btn-lg btn-primary pull-xs-right">
            {{isLogin=='login'?'Sign In':'Sign Up'}}
          </button>
        </form>
      </div>

    </div>
  </div>
</div>
</template>
<script>
import {login,register} from '@/api/user'
const Cookie = process.client ? require('js-cookie'):undefined // 仅在客户端加载js-cookie，process.client是nuxt提供的判断是否是客户端
export default {
    middleware:'notAuthenticated',
    name:'LoginIndex',
    computed:{
        isLogin(){
            return this.$route.name
        }
    },
    data(){
        return {
            user:{
                username:'',
                email:'',
                password:''
            },
            errors:{}
        }
    },
    methods:{
        async onSubmit(){
          try {
            const { data } =  this.isLogin == 'login'? await login({
              user:this.user
            }): await register({
              user:this.user
            })
            // 存储用户状态，要考虑在客户端、服务端都可以拿到此状态。
            this.$store.commit('setUser',data.user)
            // 持久化用户登录信息
            Cookie.set('user',data.user)
            this.$router.push('/')

          } catch (error) {
            this.errors = error.response.data.errors
          }
            
        }
    }
}
</script>